﻿//using KingerRobot.Logging;

using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using static System.Runtime.InteropServices.JavaScript.JSType;
using K8.CBB;
using static K8.CBB.XID;

namespace KingerRobot.MexicoSailunMES.SpiService;
public class MesImpl : IMesService
{

    public List<BcdInfoBean> GetMesNoSyncProduct()
    {
        var db = Db.Default;
        var result = db.BcdInfos.Where(t => t.RcvFlag != "Y").ToList().Select(t => new BcdInfoBean
        {
            BcdNo = t.BcdNo,
            TbmSpec = t.TbmSpec,
            TbmSpecDesc = t.TbmSpecDesc,
            TbmSpecVer = t.TbmSpecVer,
            TbmExpirationTime = t.TbmExpirationTime,
            TbmPs = t.TbmPs,
            TbmNo = t.TbmNo,
            ProdDt = t.ProdDt,
            StdWt = t.StdWt,
            MinWt = t.MinWt,
            MaxWt = t.MaxWt,
            InPermit = t.InPermit,
            RcvFlag = t.RcvFlag,
            RegDt = t.RegDt,
            Rfid = "",//t.Rfid,
            Relateequipmen = t.Relateequipment,
            Remarks = "",//t.Remarks,
            HEIGHT = t.HEIGHT,
            //CreateTime = t.CreateTime,
            //UpdateTime = t.UpdateTime,
            //UseFlag = t.UseFlag,
        }).ToList();
        return result;
    }

    public List<HoldReqInfoBean> GetMesNoSyncHoldReq()
    {
        var db = Db.Default;

        var mesHoldReqs = db.MesHoldReqs.Where(t => t.RcvFlag == "0").ToList();
        if (mesHoldReqs == null || mesHoldReqs.Count() == 0)
        {
            return null;
        }
        var result = mesHoldReqs.Where(t => t.UpdDt >= DateTime.Now.AddHours(-7)).ToList().Select(t => new HoldReqInfoBean
        {

            BcdNo = t.BcdNo,
            ErrCd = t.ErrCd,
            ErrDesc = t.ErrDesc,
            RcvFlag = t.RcvFlag,
            RegDt = t.RegDt.GetValueOrDefault(),
            UpdDt = t.UpdDt.GetValueOrDefault(),
        }).ToList();
        return result;
    }

    public List<TcmInfo> GetRequestMaterialInfos()
    {
        var db = Db.Default;

        var reqAndSpecs = db.TcmGtReqs
            .Where(t => t.GtReq == "Y" || t.LdGt == "N" || t.CvGt == "N")
            .Join(db.TcmGtSpecs, f => f.TcmNo, s => s.TcmDir, (f, s) => new
            {
                Req = f,
                Spec = s,
            }).ToList();

        List<TcmInfo> infos = new List<TcmInfo>();

        foreach (var reqAndSpec in reqAndSpecs)
        {
            infos.Add(TcmInfo.Create(reqAndSpec.Spec, reqAndSpec.Req));
        }
        return infos.OrderBy(f => f.REQ_REG_DT).ToList();
    }

    public int UpdateBcdInfoRcvFlag(string bcdNo)
    {

        try
        {
            var db = Db.Default;

            var info = db.BcdInfos.Where(t => t.BcdNo == bcdNo).Update(new POBcdInfo
            {
                RcvFlag = "Y",
            });

            var result = db.SaveChanges();
            return info;
        }
        catch (Exception ex)
        {
            K8.LSF.Client.Log(new K8.LSF.Log { Data = $"回写Mes发生异常：{ex}" });
        }
        return -1;

    }

    public int UpdateHoldReqRcvFlag(string bcdNo)
    {
        var db = Db.Default;

        var result = db.MesHoldReqs.Where(f => f.BcdNo == bcdNo).Update(new POMesHoldReq { RcvFlag = "1" });
        db.SaveChanges();
        return result;
    }


    public int UpdateSpecRcvFlag(TcmInfo tcminfo)
    {

        var db = Db.Default;
        var tcmSpec = db.TcmGtSpecs.Where(f => f.TcmNo == tcminfo.TCM_NO && f.TcmDir == tcminfo.TCM_DIR).Update(new POTcmGtSpec
        {
            RcvFlag = "Y",
        });
        db.SaveChanges();

        return 1;
    }



    public InCuringDto GetInCuringInfo(string tireCode)
    {
        var dto = new InCuringDto()
        {
            TireCode = tireCode,
        };

        var db = Db.Default;
        var bcdInfo = db.BcdInfos.FirstOrDefault(item => item.BcdNo == tireCode);
        if (bcdInfo == null)
        {
            dto.Error = $"未在Mes入库信息BCD_INFO表中找到胎号为{tireCode}的记录";
            return dto;
        }

        dto.TireInfo = TireInfo.Create(bcdInfo);

        var reqAndSpecs = (from req in db.TcmGtReqs
                           join spec in db.TcmGtSpecs on new { req.TcmNo, req.TcmDir } equals new { spec.TcmNo, spec.TcmDir }
                           where spec.TbmSpec == bcdInfo.TbmSpec && (req.GtReq == "Y" || req.LdGt == "N" || req.CvGt == "N")
                           orderby req.RegDt
                           select new
                           {
                               Req = req,
                               Spec = spec,
                           }).ToList();

        foreach (var reqAndSpec in reqAndSpecs)
        {
            dto.TcmInfos.Add(TcmInfo.Create(reqAndSpec.Spec, reqAndSpec.Req));
        }

        if (dto.TcmInfos.Any())
        {
            dto.IsSuccess = true;
        }
        else
        {
            dto.Error = $"未找到符合条件的硫化机信息。胎号：{bcdInfo.BcdNo}，物料号：{bcdInfo.TbmSpec}";
        }

        return dto;
    }

    public List<TcmInfo> GetAllInCuringInfos()
    {
        var db = Db.Default;

        var reqAndSpecs = (from req in db.TcmGtReqs
                           join spec in db.TcmGtSpecs on new { req.TcmNo, req.TcmDir } equals new { spec.TcmNo, spec.TcmDir }
                           //where ((spec.RcvFlag == "N") && (req.GtReq == "Y" || req.LdGt == "N" || req.CvGt == "N"))
                           where (spec.RcvFlag == "N" && req.GtReq == "Y" && req.CvGt == "N")
                           orderby req.RegDt
                           select new
                           {
                               Req = req,
                               Spec = spec,
                           }).ToList();

        List<TcmInfo> infos = new List<TcmInfo>();

        foreach (var reqAndSpec in reqAndSpecs)
        {
            infos.Add(TcmInfo.Create(reqAndSpec.Spec, reqAndSpec.Req));
        }

        var result = infos.OrderBy(f => f.REQ_REG_DT).ToList();

        XLogHelper.WriteLog($"GetAllInCuringInfos:{DateTime.Now.ToShortDateString}/{result.ToJson()}", true);
        return result;
    }

    public List<Bean> GetAllOrderInfos()
    {
        var db = Db.Default;

        var reqAndSpecs = (from req in db.TcmGtReqs
                           join spec in db.TcmGtSpecs on new { req.TcmNo, req.TcmDir } equals new { spec.TcmNo, spec.TcmDir }
                           //where ((spec.RcvFlag == "N") && (req.GtReq == "Y" || req.LdGt == "N" || req.CvGt == "N"))
                           //  where (spec.RcvFlag == "N" && req.GtReq == "Y" && req.CvGt == "N")
                           orderby req.RegDt
                           select new Bean
                           {
                               Req = req,
                               Spec = spec,
                           }).ToList();

        return reqAndSpecs;
    }

    public List<TcmInfo> GetWMSAllInCuringInfos()
    {
        var db = Db.Default;

        var reqAndSpecs = (from req in db.TcmGtReqs
                           join spec in db.TcmGtSpecs on new { req.TcmNo, req.TcmDir } equals new { spec.TcmNo, spec.TcmDir }
                           //where ((spec.RcvFlag == "N") && (req.GtReq == "Y" || req.LdGt == "N" || req.CvGt == "N"))
                           //where (spec.RcvFlag == "N" && req.GtReq == "Y" && req.CvGt == "N")
                           orderby req.RegDt
                           select new
                           {
                               Req = req,
                               Spec = spec,
                           }).ToList();

        List<TcmInfo> infos = new List<TcmInfo>();

        foreach (var reqAndSpec in reqAndSpecs)
        {
            infos.Add(TcmInfo.Create(reqAndSpec.Spec, reqAndSpec.Req));
        }


        return infos.OrderBy(f => f.TCM_NO).ToList();
    }

    public List<TcmStatusBean> GetTcmStatus()
    {
        var db = Db.Default;
        var beans = (from req in db.TcmGtReqs
                     join spec in db.TcmGtSpecs on new { req.TcmNo, req.TcmDir } equals new { spec.TcmNo, spec.TcmDir }
                     select new TcmStatusBean
                     {
                         TCM_NO = req.TcmNo,
                         TCM_DIR = req.TcmDir,
                         LD_GT = req.LdGt,
                         CV_GT = req.CvGt,
                         GT_REQ = req.GtReq,
                         SULFOPEN_TIME =req.SulfopenTime.GetValueOrDefault().ToUniversalTime(),
                         REG_DT = req.RegDt.GetValueOrDefault().ToUniversalTime(),
                         TCM_SPEC = spec.TbmSpec,
                         TCM_SPEC_DESC = spec.TbmSpecDesc,
                         RcvFlag=spec.RcvFlag,
                     }).ToList();
        return beans;
    }

    public int AddOutEnds(List<EndParam> endParams)
    {
        var db = Db.Default;

        foreach (var param in endParams)
        {
            //胎胚信息
            var tireInfo = db.BcdInfos.Where(f => f.BcdNo == param.TirCode).FirstOrDefault();
            //硫化物料
            var tcmGtSpec = db.TcmGtSpecs.Where(f => f.TcmNo == param.TcmNo && f.TcmDir == param.TcmDir).FirstOrDefault();

            POOutEnd bean = new POOutEnd()
            {
                TcmNo = param.TcmNo,
                TcmDesc = tcmGtSpec.TcmDesc,
                TcmDir = param.TcmDir,
                TcmSpec = param.TcmSpec,
                TcmSpecDesc = param.TcmSpecDesc,
                BcdNo = param.TirCode,
                TbmSpec = tireInfo.TbmSpec,
                TbmSpecDesc = tireInfo.TbmSpecDesc,
                TcmAngle = param.Angle,
                TbmSpecVer = tireInfo.TbmSpecVer,
                TbmExpirationTime = tireInfo.TbmExpirationTime.GetValueOrDefault().ToUniversalTime(),
                TbmPs = param.TbmPs,
                RcvFlag = "0",
                CompFlag = param.CompFlag,
            };

            db.OutEnds.Add(bean);
        }

        return db.SaveChanges();
    }

    public InCuringDto GetTireInfos(string tireCode)
    {
        var db = Db.Default;
        try
        {
            K8.LSF.Client.Log(new K8.LSF.Log { Data = $"开始获取胎胚信息：{tireCode}" });
            var tireInfos = db.BcdInfos.Where(f => f.BcdNo == tireCode).ToList();
            // K8.LSF.Client.Log(new K8.LSF.Log { Data = $"获取胎胚信息{tireCode}完成：{tireInfos?.ToJson()}" });
            var tireInfo = tireInfos.FirstOrDefault();

            return new InCuringDto() { TireInfo = TireInfo.Create(tireInfo) };
        }
        catch (Exception ex)
        {
            K8.LSF.Client.Log(new K8.LSF.Log { Data = $"开始获取胎胚信息：{tireCode}异常,{ex.ToString()}" });
        }
        return null;
    }

    public List<ProductInfoBean> GetNotSyncProductInfosByTbmNos(List<string> tbmNos)
    {
        var db = Db.Default;

        return db.BcdInfos.Where(f => tbmNos.Contains(f.TbmNo) && (f.RcvFlag == "N")).Select(info => new ProductInfoBean
        {
            BCD_NO = info.BcdNo,
            TBM_SPEC = info.TbmSpec,
            TBM_SPEC_DESC = info.TbmSpecDesc,
            TBM_NO = info.TbmNo,
            HEIGHT = info.HEIGHT,
            IN_PERMIT = info.InPermit,
            MAX_WT = info.MaxWt,
            STD_WT = info.StdWt,
            MIN_WT = info.MinWt,
            PROD_DT = info.ProdDt,
            REG_DT = info.RegDt,
            RELATEEQUIPMENT = info.Relateequipment,
            TBM_EXPIRATION_TIME = info.TbmExpirationTime,
            TBM_PS = info.TbmPs,
            TBM_SPEC_VER = info.TbmSpecVer,
        }).Take(1000).ToList();
    }

    public ProductInfoBean GetProductInfosByBcdNo(string bcdNo)
    {
        var db = Db.Default;
        K8.LSF.Client.Log(new K8.LSF.Log { Data = $"获取胎胚信息完成2222" });
        try
        {
            var infos = db.BcdInfos.Where(f => f.BcdNo == bcdNo).ToList();
            var info = infos.FirstOrDefault();
            K8.LSF.Client.Log(new K8.LSF.Log { Data = $"获取胎胚信息完成333" });
            if (info is null)
            {
                return null;
            }

            ProductInfoBean result = new()
            {
                BCD_NO = info.BcdNo,
                TBM_SPEC = info.TbmSpec,
                TBM_SPEC_DESC = info.TbmSpecDesc,
                TBM_NO = info.TbmNo,
                HEIGHT = info.HEIGHT,
                IN_PERMIT = info.InPermit,
                MAX_WT = info.MaxWt,
                STD_WT = info.StdWt,
                MIN_WT = info.MinWt,
                PROD_DT = info.ProdDt,
                REG_DT = info.RegDt,
                RELATEEQUIPMENT = info.Relateequipment,
                TBM_EXPIRATION_TIME = info.TbmExpirationTime,
                TBM_PS = info.TbmPs,
                TBM_SPEC_VER = info.TbmSpecVer,
            };
            return result;
        }
        catch (Exception ex)
        {
            K8.LSF.Client.Log(new K8.LSF.Log { Data = $"获取胎胚信息异常222：{ex.ToString()}" });
        }
        return null;
    }

    public int AddInEndByBcdNos(string bcdNo, string LocCode)
    {

        K8.LSF.Client.Log(new K8.LSF.Log { Data = $"开始新增入库推送1111：{bcdNo}" });
        try
        {
            var info = GetProductInfosByBcdNo(bcdNo);
            //K8.LSF.Client.Log(new K8.LSF.Log { Data = $"开始获取胎胚信息1111：{info.ToJson()}" });
            if (info is null)
            {
                return -1;
            }

            info.RACK_ADD = LocCode;

            var result = AddInEnd(info);
            //K8.LSF.Client.Log(new K8.LSF.Log { Data = $"开始新增入库推送返回结果111：{result}" });
            return result;
        }
        catch (Exception ex)
        {
            K8.LSF.Client.Log(new K8.LSF.Log { Data = $"开始新增入库推送异常1111：{ex.ToString()}" });
        }
        return 0;
    }

   
  
    public List<BcdLockInfo> GetLocInfos()
    {
        var db = Db.Default;

        return db.MesHoldReqs.Where(f => f.RcvFlag == "0").Select(f => new BcdLockInfo
        {
            BCD_NO = f.BcdNo,
            ERR_CD = f.ErrCd,
            ERR_DESC = f.ErrDesc,
        }).ToList();
    }

    public List<BcdLockInfo> GetLocInfosByProductCodes(List<string> barCodes)
    {
        var db = Db.Default;

        return db.MesHoldReqs.Where(f => barCodes.Contains(f.BcdNo) && f.RcvFlag == "0").Select(f => new BcdLockInfo
        {
            BCD_NO = f.BcdNo,
            ERR_CD = f.ErrCd,
            ERR_DESC = f.ErrDesc,
        }).ToList();
    }


    public int AddInEnd(ProductInfoBean info)
    {
        var db = Db.Default;
        POInEnd inEnd = new POInEnd()
        {
            BcdNo = info.BCD_NO,
            MaxWt = info.MAX_WT,
            InPermit = info.IN_PERMIT,
            MinWt = info.MIN_WT,
            ProdDt = info.PROD_DT.GetValueOrDefault().ToUniversalTime(),
            RcvFlag = "0",
            RegDt = info.REG_DT.GetValueOrDefault().ToUniversalTime(),
            StdWt = info.STD_WT,
            TbmExpirationTime = info.TBM_EXPIRATION_TIME.GetValueOrDefault().ToUniversalTime(),
            TbmNo = info.TBM_NO,
            TbmPs = info.TBM_PS,
            TbmSpec = info.TBM_SPEC,
            TbmSpecDesc = info.TBM_SPEC_DESC,
            TbmSpecVer = info.TBM_SPEC_VER,
            UpdDt = DateTime.UtcNow,
            //ERR_CD = info.ERR_CD,
            RackAdd = info.RACK_ADD
        };
        var result = db.InEnds.Insert(inEnd);
        db.SaveChanges();
        return result;
    }

    public int AddOutEnds(EndParam endParam)
    {
        var db = Db.Default;
        //胎胚信息
        var tireInfo = db.BcdInfos.Where(f => f.BcdNo == endParam.TirCode).FirstOrDefault();
        //硫化物料
        var tcmGtSpec = db.TcmGtSpecs.Where(f => f.TcmNo == endParam.TcmNo && f.TcmDir == endParam.TcmDir).FirstOrDefault();

        POOutEnd bean = new POOutEnd()
        {
            TcmNo = endParam.TcmNo,
            TcmDesc = tcmGtSpec.TcmDesc,
            TcmDir = endParam.TcmDir,
            TcmSpec = endParam.TcmSpec,
            TcmSpecDesc = endParam.TcmSpecDesc,
            BcdNo = endParam.TirCode,
            TbmSpec = tireInfo.TbmSpec,
            TbmSpecDesc = tireInfo.TbmSpecDesc,
            TcmAngle = endParam.Angle,
            TbmSpecVer = tireInfo.TbmSpecVer,
            TbmExpirationTime = tireInfo.TbmExpirationTime.GetValueOrDefault().ToUniversalTime(),
            TbmPs = endParam.TbmPs,
            RcvFlag = "0",
            CompFlag = endParam.CompFlag,
        };

        db.OutEnds.Insert(bean);
        db.SaveChanges();
        return 1;
    }

    public List<CuringStatusBean> GetCuringStatusBeans(CuringStatusParam param)
    {
        var db = Db.Default;

        var tcmNo = param?.TCM_NO;
        var tcmdDir = param?.TCM_DIR;
        var tcmSpec = param?.TCM_SPEC;

        var list = (from status in db.TcmGtReqs
                    join spec in db.TcmGtSpecs on new { status.TcmNo, status.TcmDir } equals new { spec.TcmNo, spec.TcmDir }
                    where (string.IsNullOrWhiteSpace(tcmNo) || spec.TcmNo.Contains(tcmNo)) &&
                          (string.IsNullOrWhiteSpace(tcmdDir) || spec.TcmDir == tcmdDir) &&
                          (string.IsNullOrWhiteSpace(tcmSpec) || spec.TbmSpec == tcmSpec)
                    select new CuringStatusBean
                    {
                        TCM_NO = spec.TcmNo,
                        TCM_DIR = spec.TcmDir,
                        TCM_SPEC = spec.TbmSpec,
                        CV_GT = status.CvGt == "N" ? "无胎" : "有胎",
                        GT_REQ = status.GtReq == "Y" ? "请料" : "未请料",
                        LD_GT = status.LdGt == "N" ? "无胎" : "有胎",
                        Max_Send_Count = GetMaxRequireCount(status.GtReq, status.LdGt, status.CvGt),
                    }).ToList();

        return list;
    }


    public static int GetMaxRequireCount(string REQ_GT_REQ, string REQ_LD_GT, string REQ_CV_GT)
    {
        int maxCount = 0;

        if (REQ_GT_REQ == "X" || REQ_LD_GT == "X" || REQ_CV_GT == "X")
        {
            //硫化机，机械臂，存胎器，任意一个禁用，停止送胎
            return maxCount;
        }

        //if (REQ_GT_REQ == "Y")
        //{
        //    maxCount += 1;
        //}
        if (REQ_LD_GT == "N")
        {
            maxCount += 1;
        }
        if (REQ_CV_GT == "N")
        {
            maxCount += 1;
        }

        return maxCount;
    }

    public int  AddOutEnd(EndParam param)
    {
        var db = Db.Default;

        //胎胚信息
        var tireInfos = db.BcdInfos.Where(f => f.BcdNo == param.TirCode).ToList();
        var tireInfo = tireInfos.FirstOrDefault();
        //硫化物料
        var tcmGtSpecs = db.TcmGtSpecs.Where(f => f.TcmNo == param.TcmNo && f.TcmDir == param.TcmDir).ToList();
        var tcmGtSpec = tcmGtSpecs.FirstOrDefault();

        POOutEnd bean = new POOutEnd()
        {
            TcmNo = param.TcmNo,
            TcmDesc = "",//param.TcmDesc"",
            TcmDir = param.TcmDir,
            TcmSpec = param.TcmSpec,
            TcmSpecDesc = param.TcmSpecDesc,
            BcdNo = param.TirCode,
            TbmSpec = tireInfo.TbmSpec,
            TbmSpecDesc = tireInfo.TbmSpecDesc,
            TcmAngle = param.Angle,
            TbmSpecVer = tireInfo.TbmSpecVer,
            TbmExpirationTime = tireInfo.TbmExpirationTime.GetValueOrDefault().ToUniversalTime(),
            TbmPs = param.TbmPs,
            RcvFlag = "0",
            CompFlag = param.CompFlag,
            RegDt = DateTime.UtcNow,
        };

        db.OutEnds.Add(bean);


        return db.SaveChanges();
    }
}
